<?php
/**
 * 博客前台搜索模型，负责数据，增，删，改，查
 * 因为没有博客数据没使用数据库，所以没有继承 Model 类
 */
Class SearchModel extends PublicModel{

	/**
	 * 搜索数据处理
	 * @param  [type] $id [接收ID]
	 * @return [type]     [description]
	 */
	Public function getFileIds($id){
		$C = $this->blogConfig();
		$need = $this->searchFile($id);
		if (!empty($need)) {
				foreach ($need as $k => $v) {
					$array[] = unfile(C('post.postdata').$k.'.Mark');
				}
		}
	
		$data = $this->getunFile($array);
		if (!$data) return;
		$indexpage = $C['site_mumber'];
		$count = count($data);
		$lastpage = ceil($count / $indexpage);
		$getp = trim(G('get.p'));
		$pagenum = (!empty($getp)) ? G('get.p') : 1;
		$pageurl = U('search/s', array('s' => $id), true);
		$page = new Page($count, $indexpage, $pageurl);
		$pnum = explode(',', $page->limit());
		for ($i=0; $i < $count; $i++) {
			if ($i < $pnum[0] || $i >= $pnum[0] + $pnum[1]) continue;
				$lastarr[] = $data[$i];
		}
		$redata['sfile'] = $lastarr;
		$redata['page'] = $page->view();
		return $redata;
	}

	/**
	 * 搜索本地文件加快搜索速度
	 * @param  [type] $keyword [接收搜索内容]
	 * @return [type]          [description]
	 */
	Public function searchFile($keyword) {
		$dir = C('post.postdata');
		$sFile = GetFileList($dir);
		if (count($sFile) <= 0) {
			return false;
		}
		$sResult = array();
		foreach ($sFile as $file) {
			if (!$fp = file_get_contents($dir.$file)) {
				if (APP_DEBUG) {
					Debug::add('不能打开'.$dir.$file.'文件!');
				} else {
					return false;
				}
			}
			if (preg_match("/$keyword/i", $fp)) {
				$sResult[] = $file;
			}
		}
		if (count($sResult) <= 0) {
			return false;
		} else {
			foreach ($sResult as $k => $v) {
				$sResult[$k] = str_replace('.Mark', '', $v);
			}
			$filemode = $this->getPost();
			$filemode = Arr::getArray($filemode);
			foreach ($filemode as $k => $v) {
				foreach ($sResult as $q => $z) {
					if (strstr(strtolower($z), strtolower($k)) == true) {
						$lastarr[$k] = $v;
					}
				}
			}
			return $lastarr;
		}
	}
}